package com.tledu.pipeline;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NewsPipeline implements Pipeline {

    @Override
    public void process(ResultItems resultItems, Task task) {
        // 针对任务进行处理，获取到resultItems，处理里面的数据
        String title = resultItems.get("title");
        // time是日期类型的，进行日期的格式化
        Date time = resultItems.get("time");
        String content = resultItems.get("content");
        String url = resultItems.getRequest().getUrl();
        String contentHtml = resultItems.get("contentHtml");
        String author = resultItems.get("author");
        String category = resultItems.get("category");
        String source = resultItems.get("source");
        // 所有的字段都准备好了，入库
        // jdbc的流程也比较固定
        // 1. 装载依赖
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 创建数据库的连接
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/jingmao20",
                    "root",
                    "root"
            );
            // 查询操作
            // todo 定义sql模板
            String sql = "insert into news(url, title, time, content, content_html, category, source, author) " +
                    "value (?,?,?,?,?,?,?,?)";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);

            // todo 设置参数
            int i = 1;
            preparedStatement.setString(i++,url);
            preparedStatement.setString(i++,title);
            // java.sql.Date只有年月日
            // java.sql.Time只有时分秒
            // java.sql.Timestamp 包含年月日和时分秒
            // java.util.Date 转成 java.sql.Date
            preparedStatement.setTimestamp(i++,new Timestamp(time.getTime()));
            preparedStatement.setString(i++,content);
            preparedStatement.setString(i++,contentHtml);
            preparedStatement.setString(i++,category);
            preparedStatement.setString(i++,source);
            preparedStatement.setString(i++,author);
            // todo 执行sql  execute 和 executeQuery（执行查询操作之后得到resultSet，通过resultSet拿到查询结果）
            preparedStatement.execute();

            preparedStatement.close();
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}
